package com.piggymetrics.gateway;

import com.gaea.tracker.GatewayTracker;
import com.gaea.tracker.common.Identifier;
import com.gaea.tracker.common.IdentifierKey;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import javax.servlet.http.HttpServletRequest;

import static com.netflix.zuul.context.RequestContext.getCurrentContext;


public class MyPreFilter extends ZuulFilter {

  private Log logger = LogFactory.getLog(MyPreFilter.class);

  /**
   * 过滤器执行的具体逻辑
   * 只有URL后面有accToken的才被允许访问
   */
  public Object run() {
    RequestContext ctx = getCurrentContext();
    HttpServletRequest request = ctx.getRequest();
    logger.info(System.getenv("REDIS_IP"));
    logger.info(String.format("send %s request to %s", request.getMethod(), request.getRequestURL().toString()));

    GatewayTracker tracker = GatewayTracker.newInstance(request, "gateway");

    tracker.trackInEvent(request);

    //从Tracker 获取identifier 并 添加到 request 中
    Identifier identifier = tracker.generateIdentifier();
    ctx.addZuulRequestHeader(IdentifierKey.URL.toString(), identifier.getUrl());
    ctx.addZuulRequestHeader(IdentifierKey.REQUESTID.toString(), identifier.getRequestId());
    ctx.addZuulRequestHeader(IdentifierKey.SERVICENAME.toString(), identifier.getServiceName());
    ctx.addZuulRequestHeader(IdentifierKey.STAGE.toString(), identifier.getStage());
    ctx.addZuulRequestHeader(IdentifierKey.CALLID.toString(), identifier.getCallId());
    tracker.trackOutEvent(identifier.getCallId());

    return null;
  }

  /**
   * 判断过滤器是否需要被执行
   */
  public boolean shouldFilter() {
    return true;
  }

  /**
   * 过滤器执行顺序,数字越小优先级越高
   */
  public int filterOrder() {
    return 0;
  }

  /*
   * 定义过滤器类型，决定该规则处理请求的哪个生命周期执行，有以下四个阶段：
   * pre: 在请求被路由之前执行
   * route : 在路由请求调用
   * post : 在route和err之后被调用
   * error：在处理请求发生错误时调用
   */
  public String filterType() {
    return "pre";
  }

}
